import React, { Component, Suspense } from 'react';
import { connect } from "dva";
import { routerRedux } from "dva/router";
import { Card, Button, Upload, Icon, message, Spin, Tooltip } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import PageLoading from '@/components/PageLoading';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './knowledgeGather.less';
const { Dragger } = Upload;
import wordIcon from '@/assets/knowledgeGather/u12.svg';
import pdfIcon from '@/assets/knowledgeGather/u13.svg';
import pptIcon from '@/assets/knowledgeGather/u17.svg';
import txtIcon from '@/assets/knowledgeGather/u14.svg';
import textIcon from '@/assets/knowledgeGather/u29.svg';
import tableIcon from '@/assets/knowledgeGather/u30.svg';
import u33Icon from '@/assets/knowledgeGather/u33.png';
import u34Icon from '@/assets/knowledgeGather/u34.png';
import u26Icon from '@/assets/knowledgeGather/u26.svg';

import u37Icon from '@/assets/knowledgeGather/u37.png';
import u41Icon from '@/assets/knowledgeGather/u41.png';
import u54Icon from '@/assets/knowledgeGather/u54.png';
import u55Icon from '@/assets/knowledgeGather/u55.png';
import u56Icon from '@/assets/knowledgeGather/u56.png';
import u60Icon from '@/assets/knowledgeGather/u60.png';
import u62Icon from '@/assets/knowledgeGather/u62.png';
import u63Icon from '@/assets/knowledgeGather/u63.png';
import u66Icon from '@/assets/knowledgeGather/u66.png';

import { getKnowledgeCollectStatus, editDocStart, uploadFile } from '@/services/knowledgeGather';
import { getFileInfo } from "@/services/knowledgeFile";

var checkInterval = null;

class KnowledgeGather extends Component {
    constructor(props) {
        super(props);
        this.state = {
            uploading: false,
        }
    }

    componentDidMount() {
        if (checkInterval) { clearInterval(checkInterval) };
        this.getCurrentStatus()
    }

    getCurrentStatus = async () => {
        let res = await getKnowledgeCollectStatus();
        console.log(res);

        const { dispatch } = this.props;
        let pathname = "";
        // dispatch(routerRedux.push({ pathname }));

        switch (res.status) {
            case '0':           // 初始页面
                pathname = "";
                break;

            case '1':           // 自定义文档页
                pathname = "/knowledgeDesign/knowledgeCollect/addMarkdownFile";
                dispatch(routerRedux.push({ pathname }));
                break;

            case '2':           // 文档预览
                pathname = "/knowledgeDesign/knowledgeCollect/addUploadFile";
                dispatch(routerRedux.push({ pathname, query: { docId: res.docId, docPath: encodeURI(res.previewPath) } }));
                break;

            case '3':           // 问题生成中
                pathname = "/knowledgeDesign/knowledgeCollect/generateQuestion";
                dispatch(routerRedux.push({ pathname }));
                break;

            case '4':           // 问题展示
                pathname = "/knowledgeDesign/knowledgeCollect/questionLibrary";
                dispatch(routerRedux.push({ pathname }));
                break;

            case '5':           // 答案生成中
                pathname = "/knowledgeDesign/knowledgeCollect/generateAnswer";
                dispatch(routerRedux.push({ pathname }));
                break;

            case '6':           // 答案展示
                pathname = "/knowledgeDesign/knowledgeCollect/questionAnswerList";
                dispatch(routerRedux.push({ pathname }));
                break;

            default:
                break;
        }
    }

    routerTextClick = async () => {
        let res = await editDocStart();
        console.log(res);
        if (res.code === 0) {
            const { dispatch } = this.props;
            let pathname = "/knowledgeDesign/knowledgeCollect/addMarkdownFile";
            dispatch(routerRedux.push({ pathname }));
        }
    }

    routerFileClick = (id, path) => {
        const { dispatch } = this.props;
        let pathname = "/knowledgeDesign/knowledgeCollect/addUploadFile";
        dispatch(routerRedux.push({ pathname, query: { docId: id, docPath: encodeURI(path) } }));
    }

    getFileNameType = (fileName) => {
		let type = fileName ? fileName.split('.') ? fileName.split('.').length > 1 ? fileName.split('.')[fileName.split('.').length-1] : null : null : null;
		return type;
	};

    onFileChange = async (info) => {
        let that = this;
        if (info.file.size > 30 * 1024 * 1024) {
            message.error(formatMessage({ id: 'knowledgeGather.upload.sizeLimit' }));
            return;
        } else if (
            this.getFileNameType(info.file.name).toLowerCase() !== 'txt' &&
			this.getFileNameType(info.file.name).toLowerCase() !== 'pdf' &&
			this.getFileNameType(info.file.name).toLowerCase() !== 'doc' &&
			this.getFileNameType(info.file.name).toLowerCase() !== 'docx' &&
			this.getFileNameType(info.file.name).toLowerCase() !== 'xls' &&
			this.getFileNameType(info.file.name).toLowerCase() !== 'xlsx' &&
			this.getFileNameType(info.file.name).toLowerCase() !== 'ppt' &&
			this.getFileNameType(info.file.name).toLowerCase() !== 'pptx' &&
			this.getFileNameType(info.file.name).toLowerCase() !== 'md'
        ) {
            message.error(formatMessage({ id: 'knowledgeGather.upload.formatLimit' }));
            return;
        } else {
            this.setState({ uploading: true })
            let formData = new FormData();
            formData.append("file", info.file);

            let res = await uploadFile(formData);
            console.log(res);
            if (res.code == 0) {
                // message.success('上传成功！');
                if(res.data.syncStatus != 4) {
                    checkInterval = setInterval(() => {
                        that.getFileItemInfo(res.data.id)
                    }, 3000)
                } else {
                    if (checkInterval) { clearInterval(checkInterval) };
                    that.setState({ uploading: false });
                    that.routerFileClick(res.data.id, res.data.previewPath);
                };
            }
        }
    };

    getFileItemInfo = async (id) => {
		let res = await getFileInfo({ id });
		console.log(res);
		if (res.code == 0) {
            if(res.data.syncStatus == 4) {
                if (checkInterval) { clearInterval(checkInterval) };
                this.setState({ uploading: false });
                this.routerFileClick(res.data.id, res.data.previewPath);
            };
        }
	};

    render() {
        const antIcon = <Icon type="loading" style={{ fontSize: 24 }} spin />;
        const props = {
            // name: 'file',
            multiple: false,
            showUploadList: false,
            beforeUpload: () => {
                return false;
            },
            // action: '/cloud/knowledgeCollect/doc/upload',
            accept: ".txt,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.md",
            onChange: this.onFileChange,
        };

        return (
            <Suspense fallback={<PageLoading />}>
                <PageHeaderWrapper>
                    <div>
                        <Card bordered={false} style={{ margin: '0 0 12px' }}>
                            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                <Tooltip placement="bottomLeft" arrowPointAtCenter overlayStyle={{ maxWidth: '400px' }} title="请上传所需采编和编辑的知识点原始文档，或自行编写相关文档。">
                                    <div className={styles.cardIcon}>
                                        <div style={{ marginBottom: 8 }}><img src={u37Icon} width="56" /></div>
                                        <div style={{ lineHeight: '24px' }}>{formatMessage({ id: 'knowledgeGather.steps.selectDoc' })}</div>
                                    </div>
                                </Tooltip>
                                <div style={{ marginBottom: 32 }}><img src={u54Icon} width="56" /></div>
                                <Tooltip placement="bottomLeft" arrowPointAtCenter overlayStyle={{ maxWidth: '400px' }} title="请指定要进行采编的文档页码，并设置希望生成的问题数量。如果生成问题的数量设置为零，则需要手动添加问题，以便继续进行下一步操作。">
                                    <div className={styles.cardIcon}>
                                        <div style={{ marginBottom: 8 }}><img src={u41Icon} width="56" /></div>
                                        <div style={{ lineHeight: '24px' }}>{formatMessage({ id: 'knowledgeGather.steps.selectPage' })}</div>
                                    </div>
                                </Tooltip>
                                <div style={{ marginBottom: 32 }}><img src={u54Icon} width="56" /></div>
                                <Tooltip placement="bottom" arrowPointAtCenter overlayStyle={{ maxWidth: '400px' }} title="在处理大量文档数据时，生成问题的步骤可能需要一些时间，但这个过程是异步执行的，可以在稍后查看。">
                                    <div className={styles.cardIcon}>
                                        <div style={{ marginBottom: 8 }}><img src={u55Icon} width="56" /></div>
                                        <div style={{ lineHeight: '24px' }}>{formatMessage({ id: 'knowledgeGather.steps.generateQuestions' })}</div>
                                    </div>
                                </Tooltip>
                                <div style={{ marginBottom: 32 }}><img src={u54Icon} width="56" /></div>
                                <Tooltip placement="bottom" arrowPointAtCenter overlayStyle={{ maxWidth: '400px' }} title="你可以选择筛选特定问题或添加自定义问题，并且能够查找这批问题中与之相似度较高的问题，具备删除或将其添加为相似问题的功能。">
                                    <div className={styles.cardIcon}>
                                        <div style={{ marginBottom: 8 }}><img src={u56Icon} width="56" /></div>
                                        <div style={{ lineHeight: '24px' }}>{formatMessage({ id: 'knowledgeGather.steps.filterQuestions' })}</div>
                                    </div>
                                </Tooltip>
                                <div style={{ marginBottom: 32 }}><img src={u54Icon} width="56" /></div>
                                <Tooltip placement="bottom" arrowPointAtCenter overlayStyle={{ maxWidth: '400px' }} title="在筛选出问题后，你可以进行下一步的配置，包括设定答案要求、屏蔽词、免责声明和源链接。此外，你可以选择是否同时生成相似问题。">
                                    <div className={styles.cardIcon}>
                                        <div style={{ marginBottom: 8 }}><img src={u60Icon} width="56" /></div>
                                        <div style={{ lineHeight: '24px' }}>{formatMessage({ id: 'knowledgeGather.steps.answerRequirements' })}</div>
                                    </div>
                                </Tooltip>
                                <div style={{ marginBottom: 32 }}><img src={u54Icon} width="56" /></div>
                                <Tooltip placement="bottom" arrowPointAtCenter overlayStyle={{ maxWidth: '400px' }} title="虽然生成答案的过程可能需要较长时间，但这一步骤是异步执行的，允许您在等待期间取消操作。同时，您可以随时检查进度状态。">
                                    <div className={styles.cardIcon}>
                                        <div style={{ marginBottom: 8 }}><img src={u62Icon} width="56" /></div>
                                        <div style={{ lineHeight: '24px' }}>{formatMessage({ id: 'knowledgeGather.steps.generateAnswers' })}</div>
                                    </div>
                                </Tooltip>
                                <div style={{ marginBottom: 32 }}><img src={u54Icon} width="56" /></div>
                                <Tooltip placement="bottomRight" arrowPointAtCenter overlayStyle={{ maxWidth: '400px' }} title="在生成答案之后，您可以查阅相关的知识点，并可以修改问题和答案。此外，您还可以调整模型回答的片段，以重新生成答案。">
                                    <div className={styles.cardIcon}>
                                        <div style={{ marginBottom: 8 }}><img src={u63Icon} width="56" /></div>
                                        <div style={{ lineHeight: '24px' }}>{formatMessage({ id: 'knowledgeGather.steps.reviewAnswers' })}</div>
                                    </div>
                                </Tooltip>
                                <div style={{ marginBottom: 32 }}><img src={u54Icon} width="56" /></div>
                                <Tooltip placement="bottomRight" arrowPointAtCenter overlayStyle={{ maxWidth: '400px' }} title="生成的知识点在选择特定范围后，可以添加到本地知识库中。一旦添加，您便能够在咨询窗口中使用这些知识进行问答。">
                                    <div className={styles.cardIcon}>
                                        <div style={{ marginBottom: 8 }}><img src={u66Icon} width="56" /></div>
                                        <div style={{ lineHeight: '24px' }}>{formatMessage({ id: 'knowledgeGather.steps.addToKnowledgeBase' })}</div>
                                    </div>
                                </Tooltip>
                            </div>
                        </Card>
                        <Card bordered={false} title={<span style={{ fontWeight: 'bold' }}>{formatMessage({ id: 'knowledgeGather.card.title' })}</span>} style={{ margin: '0 0 12px' }}>
                            <div style={{ display: 'flex', gap: '20px', justifyContent: 'space-between' }}>
                                <div>
                                    <p style={{ fontWeight: 'bold', marginBottom: 30 }}>{formatMessage({ id: 'knowledgeGather.upload.title' })}</p>
                                    <div style={{ display: 'flex', gap: '24px' }}>
                                        <div style={{ textAlign: 'center' }}>
                                            <p><img src={wordIcon} /></p>
                                            <p>Word</p>
                                        </div>
                                        <div style={{ textAlign: 'center' }}>
                                            <p><img src={pdfIcon} /></p>
                                            <p>PDF</p>
                                        </div>
                                        <div style={{ textAlign: 'center' }}>
                                            <p><img src={pptIcon} /></p>
                                            <p>PPT</p>
                                        </div>
                                        <div style={{ textAlign: 'center' }}>
                                            <p><img src={txtIcon} /></p>
                                            <p>TXT</p>
                                        </div>
                                    </div>
                                </div>
                                <div>
                                    <img src={u33Icon} width="240" />
                                </div>
                                <div style={{ width: '450px' }} className={styles["upload-card"]}>
                                    <Spin tip={formatMessage({ id: 'knowledgeGather.upload.processing' })} spinning={this.state.uploading} indicator={antIcon}>
                                        <Dragger {...props}>
                                            <div style={{ display: 'flex', gap: '60px', alignItems: 'center', margin: '0 36px' }}>
                                                <div style={{ textAlign: 'left' }}>
                                                    <p style={{ marginBottom: 12, fontSize: '16px' }}>
                                                        <a>{formatMessage({ id: 'knowledgeGather.upload.button' })}</a>
                                                        {formatMessage({ id: 'knowledgeGather.upload.dragText' })}
                                                    </p>
                                                    <p>{formatMessage({ id: 'knowledgeGather.upload.sizeText' })}</p>
                                                </div>
                                                <div>
                                                    <p><img src={u26Icon} /></p>
                                                </div>
                                            </div>
                                        </Dragger>
                                    </Spin>
                                </div>
                            </div>
                        </Card>
                        <Card bordered={false} title={<span style={{ fontWeight: 'bold' }}>{formatMessage({ id: 'knowledgeGather.custom.title' })}</span>}>
                            <div style={{ display: 'flex', gap: '20px', justifyContent: 'space-between' }}>
                                <div>
                                    <p style={{ fontWeight: 'bold', marginBottom: 30 }}>{formatMessage({ id: 'knowledgeGather.custom.subtitle' })}</p>
                                    <p style={{ marginBottom: 24 }}>{formatMessage({ id: 'knowledgeGather.custom.markdown' })}</p>
                                    <div style={{ display: 'flex', gap: '30px' }}>
                                        <div style={{ textAlign: 'center' }}>
                                            <p><img src={textIcon} /></p>
                                            <p>{formatMessage({ id: 'knowledgeGather.custom.text' })}</p>
                                        </div>
                                        <div style={{ textAlign: 'center' }}>
                                            <p><img src={tableIcon} /></p>
                                            <p>{formatMessage({ id: 'knowledgeGather.custom.table' })}</p>
                                        </div>
                                    </div>
                                </div>
                                <div>
                                    <img src={u34Icon} width="220" />
                                </div>
                                <div style={{ width: '450px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                    <Button type="primary" style={{ width: '120px' }} onClick={this.routerTextClick}>
                                        {formatMessage({ id: 'knowledgeGather.custom.button' })}
                                    </Button>
                                </div>
                            </div>
                        </Card>
                    </div>
                </PageHeaderWrapper>
            </Suspense>
        )
    }
}

export default connect(({ user }) => ({
    currentUser: user.currentUser
}))(KnowledgeGather);